#include <bits/stdc++.h>
#define stat STATE
using namespace std;
typedef long long ll;
ll N, M, A, B, W;
struct edge
{
    ll v, w;
};
vector<edge> e[1005];
struct stat
{
    ll pos, xorsum;
};
bool vis[1005][1030];
queue<stat> q;
int main()
{
    scanf("%lld%lld", &N, &M);
    for (int i = 1; i <= M; i++) {
        scanf("%lld%lld%lld", &A, &B, &W);
        e[A].push_back({ B, W });
    }
    q.push({ 1, 0 });
    vis[1][0] = 1;
    while (!q.empty()) {
        stat now = q.front(); q.pop();
        for (int i = 0; i < e[now.pos].size(); i++) {
            ll v = e[now.pos][i].v, w = e[now.pos][i].w;
            ll newxs = now.xorsum ^ w;
            if (vis[v][newxs]) continue;
            q.push({ v, newxs });
            vis[v][newxs] = 1;
        }
    }
    for (int i = 0; i < 1024; i++)
        if (vis[N][i]) {
            printf("%lld\n", i);
            return 0;
        }
    printf("-1\n");
    return 0;
}